// pay-iframe-demo.js
// 支付方页面（iframe 内部）主动获取订单信息并发起支付的示例


(function() {
  let orderInfo = null;
  let priceDetail = null;
  let token = null;
  const parentOrigin = 'https://商城域名'; // 替换为实际商城域名

  // 统一发送消息
  function sendMessage(msg) {
    window.parent.postMessage(msg, parentOrigin);
  }

  // 消息处理映射
  const handlers = {
    ORDER_INFO(data) {
      orderInfo = data.orderInfo;
      priceDetail = data.priceDetail;
      startPayment();
    },
    PAYMENT_START(data) {
      orderInfo = data.orderInfo;
      priceDetail = data.priceDetail;
      token = data.token;
      startPayment();
    },
    PAYMENT_DENY() {
      alert('支付未通过校验，无法继续');
    },
  };

  window.addEventListener('message', (event) => {
    if (event.origin !== parentOrigin) return;
    const { type } = event.data;
    if (type && handlers[type]) {
      handlers[type](event.data);
    }
  });

  // 页面加载后主动请求订单信息
  function requestOrderInfo() {
    sendMessage({ type: 'GET_ORDER_INFO' });
  }

  // 示例支付逻辑
  function startPayment() {
    if (!orderInfo || !priceDetail) {
      alert('订单信息不完整，无法支付');
      return;
    }
    // ...实际支付逻辑...
    setTimeout(() => {
      sendMessage({
        type: 'PAYMENT_RESULT',
        success: true,
        orderNo: orderInfo.orderId || '模拟订单号',
      });
    }, 1000);
  }

  // 页面加载后自动请求一次
  window.addEventListener('load', requestOrderInfo);
  window.requestOrderInfo = requestOrderInfo;

  // 动态调整iframe高度
  function adjustIframeHeight() {
    const h = Math.max(
      document.body.scrollHeight, document.body.offsetHeight,
      document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight
    );
    sendMessage({ type: 'RESIZE_HEIGHT', height: h });
  }
  window.addEventListener('load', adjustIframeHeight);
  document.addEventListener('DOMContentLoaded', adjustIframeHeight);
  new ResizeObserver(adjustIframeHeight).observe(document.body);
})();
